package com.message.Volcengine_ai_API.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class OssUtil {
        private static final String ENDPOINT = "https://oss-cn-shenzhen.aliyuncs.com";
        private static final String ACCESS_KEY_ID = "LTAI5tKeiJWnMX3bZ18xGLUo"; // KeyId
        private static final String ACCESS_KEY_SECRET = "H4bO5WhSjDR80kGpDuMaZDgfpT4f3U"; // 替换为您的 AccessKeySecret
        private static final String BUCKET_NAME = "doocassell"; // 使用已存在的Bucket名称或确保遵循命名规则
    /**
     * 上传图片到OSS
     *
     * @param objectName 目标存储中的对象键
     * @return 如果上传成功则返回true，否则返回false
     */
    public static String uploadImage(String objectName) {
        OSS ossClient = null;
        String url="";
        try {
            // 创建 OSSClient 实例
            ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            // 检查 Bucket 是否存在
            if (!ossClient.doesBucketExist(BUCKET_NAME)) {
                throw new RuntimeException("Bucket " + BUCKET_NAME + " does not exist.");
            }

            // 读取本地文件
            File file = new File("./external-resources/"+objectName);
            try (FileInputStream fis = new FileInputStream(file)) {
                // 上传文件
                PutObjectResult result = ossClient.putObject(BUCKET_NAME,objectName, fis);
                System.out.println("文件 " + "cs.png" + " 上传成功，ETag: " + result.getETag());
                url ="https://doocassell.oss-cn-shenzhen.aliyuncs.com/"+objectName;
            }
        } catch (IOException e) {
            System.err.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
    }
